package com.uchengwang.ui.cm_ui.cycle.bridge;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.http.manager.OSSManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ui.AllBaseActivity;
import com.uchengwang.ui.base_ui.ui.MainActivity;
import com.uchengwang.ui.cm_ui.cycle.bean.ActLinkEventBean;
import com.uchengwang.ui.cm_ui.cycle.bean.ImageBean;
import com.uchengwang.ui.cm_ui.cycle.bean.SetupMenusBean;
import com.uchengwang.ui.cm_ui.cycle.bean.WebViewJsBean;
import com.uchengwang.ui.cm_ui.cycle.ui.LoadCycleWebHtmlActivity;
import com.uchengwang.ui.cm_ui.cycle.ui.PlayVideoCustomActivity;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.cm_ui.release.ui.ChooseVideoActivity;
import com.uchengwang.ui.cm_ui.release.ui.ReleaseRoomMeetActivity;
import com.uchengwang.ui.cm_ui.ucity.listener.RxBusResultSubscriber;
import com.uchengwang.ui.self.jsbridge.BridgeHandler;
import com.uchengwang.ui.self.jsbridge.BridgeWebView;
import com.uchengwang.ui.self.jsbridge.CallBackFunction;
import com.uchengwang.ui.utils.ExecutorsUtils;
import com.uchengwang.ui.utils.ImageManagerUtils;
import com.uchengwang.ui.utils.JsonUtils;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.MoreOperateUtils;
import com.uchengwang.ui.utils.SPUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.finalteam.rxgalleryfinal.bean.MediaBean;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageMultipleResultEvent;
import io.rong.imlib.model.Conversation;

/**
 * BridgeWebView 注册方法
 * */
public class WebViewJsHandler {

	private String lastUrl;//上次请求调用的url地址
	private static WebViewJsHandler handler;
	private SetupMenusBean setupMenusBean;

	private WebViewJsHandler(){}
	public static WebViewJsHandler getHandler() {
		if (handler == null){
			handler = new WebViewJsHandler();
		}
		return handler;
	}

	public void registerWebviewJsHandlers(final Activity activity, BridgeWebView webView) {

		//获取用户信息
		webView.registerHandler("getUserInfo", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				//显示接收的消息
				Log.d("ryjjf", data);
				//返回给html的消息
				if (UCommonUtil.getUtil().isLogin()){
					UserBean bean = new UserBean();
					bean.setNickName(UChengApplication.nickName);
					bean.setId(UCommonUtil.getUtil().getId());
					bean.setUserAvatar(UChengApplication.userAvatar);
					bean.setUniId(UChengApplication.myUniId);
					bean.setUniName(UChengApplication.mySchoolName);
					bean.setToken(UChengApplication.TOKEN);
					bean.setMobile(SPUtils.getPreferences(activity).getUserName());
					String userInfo = JsonUtils.getManager().beanToString(bean);
					Log.d("ryjjf", "返回给h5==="+userInfo);
					function.onCallBack(userInfo);
				}else {
					Log.d("ryjjf", "返回给h5===未登录");
					function.onCallBack("");
				}

			}
		});

		webView.registerHandler("openActivity", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				//显示接收的消息
				Log.d("jjf", data);
				if (!TextUtils.isEmpty(data)){
					int index = data.indexOf("?");
					String uri = "", paras = "";
					if (index >0){
						uri = data.substring(0, index);
						Log.d("jjf", "地址URI=="+uri);
						paras = data.substring(index+1);
						Log.d("jjf", "参数=="+paras);
					}

					Intent intent = new Intent("android.intent.action.VIEW");
					if (TextUtils.isEmpty(uri)){
						intent.setData(Uri.parse(data));
					}else {
						intent.setData(Uri.parse(uri));
					}
					if (!TextUtils.isEmpty(paras)){
						if (paras.contains("&")){
							//有多个参数
							String[] p = paras.split("&");
							for (String s : p){
								String[] ps = s.split("=");
								switch (ps[0]){
									case "id":
										intent.putExtra(BaseConfig.ID, Long.parseLong(ps[1]));
										break;
									case "name":
										intent.putExtra(BaseConfig.PUB_TITLE, ps[1]);
										break;
									case "type":
										intent.putExtra(BaseConfig.TYPE, Integer.parseInt(ps[1]));
										break;
								}
							}
						}else {
							//只有一个参数
							String[] ps = paras.split("=");

							switch (ps[0]){
								case "id":
									intent.putExtra(BaseConfig.ID, Long.parseLong(ps[1]));
									break;
								case "name":
									intent.putExtra(BaseConfig.PUB_TITLE, ps[1]);
									break;
								case "type":
									intent.putExtra(BaseConfig.TYPE, Integer.parseInt(ps[1]));
									break;
							}
						}
					}
					activity.startActivity(intent);
				}
			}
		});


		//打开app加载网页
		webView.registerHandler("pushViewWithUrlAndTitle", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				//显示接收的消息
				Log.d("jjf", data);
				Log.d("jjf", "调用了111111-------------1111次"+System.currentTimeMillis());
				System.out.println("打开:"+WebViewJsHandler.this);
				//返回给html的消息
				WebViewJsBean bean = JsonUtils.getManager().stringToBean(data, WebViewJsBean.class);
				if (bean != null){
					if(!TextUtils.isEmpty(lastUrl) && lastUrl.equals(bean.getUrl())){
						//说明用户多按了一次
						return;
					}
					lastUrl = bean.getUrl();

					Intent intent = new Intent(activity, LoadCycleWebHtmlActivity.class);
					intent.putExtra(BaseConfig.URL, bean.getUrl());
					intent.putExtra(BaseConfig.IS_FULL, bean.isFull());
					intent.putExtra(BaseConfig.URL_TITLE, bean.getTitle());

					activity.startActivity(intent);
				}
			}
		});

		//关闭当前界面  打开新界面
		webView.registerHandler("replaceViewWithUrlAndTitle", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				//显示接收的消息
				System.out.println("打开:"+WebViewJsHandler.this);
				//返回给html的消息
				WebViewJsBean bean = JsonUtils.getManager().stringToBean(data, WebViewJsBean.class);
				if (bean != null){
					if(!TextUtils.isEmpty(lastUrl) && lastUrl.equals(bean.getUrl())){
						//说明用户多按了一次
						return;
					}
					lastUrl = bean.getUrl();

					Intent intent = new Intent(activity, LoadCycleWebHtmlActivity.class);
					intent.putExtra(BaseConfig.URL, bean.getUrl());
					intent.putExtra(BaseConfig.IS_FULL, bean.isFull());
					intent.putExtra(BaseConfig.URL_TITLE, bean.getTitle());

					activity.startActivity(intent);
					activity.finish();
				}
			}
		});

		//关闭activity
		webView.registerHandler("closeCurrentView", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				//显示接收的消息
				Log.d("jjf", data);
				//返回给html的消息
				activity.finish();
			}
		});

		//关闭加载h5的等待框
		webView.registerHandler("closeLoading", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				//显示接收的消息
				Log.d("jjf", data);
				//返回给html的消息
				LoadingUtils.getUtils().hide();
			}
		});

		//关闭主界面的tab
		webView.registerHandler("hideTab", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				//显示接收的消息
				Log.d("jjf", data);
				//返回给html的消息
				((MainActivity)activity).hideTab();
			}
		});

		//显示主界面的tab
		webView.registerHandler("showTab", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				//显示接收的消息
				Log.d("jjf", data);
				//返回给html的消息
				((MainActivity)activity).showTab();
			}
		});

		//h5删除数据 Finish界面  返回刷新
		webView.registerHandler("delete", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				//显示接收的消息
//				Log.d("jjf", data);
				//返回给html的消息
//				UChengApplication.isCycleDelete = true;
				activity.finish();
			}
		});

		//上传图片成功 将图片地址返回给h5
		webView.registerHandler("chooseImageAndPost", new BridgeHandler() {
			@Override
			public void handler(String data, final CallBackFunction function) {
				UCommonUtil.getUtil().openGalleryMultiple(activity, 4, new RxBusResultSubscriber<ImageMultipleResultEvent>() {
					@Override
					public void onEvent(ImageMultipleResultEvent event) {
						if (event != null && event.getResult() != null && event.getResult().size() >0){
							List<MediaBean> list = event.getResult();
							final List<String> strings = new ArrayList<>();
							for (MediaBean bean : list){
								if (!TextUtils.isEmpty(bean.getThumbnailBigPath())){
									strings.add(bean.getThumbnailBigPath());
								}else {
									strings.add(bean.getOriginalPath());
								}
							}
							LoadingUtils.getUtils().loading(activity);
							ImageManagerUtils.getUtils().compressAndPost(activity, OSSManager.OSS_SHARE, strings, 300, false, new ImageManagerUtils.ImageCompressListener() {
								@Override
								public void onResult(int stutas, String cover, final String result) {
									LoadingUtils.getUtils().hide();
									if (stutas ==0 && !TextUtils.isEmpty(result)){
										activity.runOnUiThread(new Runnable() {
											@Override
											public void run() {
												function.onCallBack(result);
											}
										});
									}
								}
							});

						}
					}
				}, null, null);
			}
		});


		//显示h5传过来的图片
		webView.registerHandler("showImages", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				//显示接收的消息
				Log.d("jjf", data);
				if (!TextUtils.isEmpty(data)){
					Gson gson = new Gson();
					ImageBean bean = gson.fromJson(data, ImageBean.class);
					int index =  bean.getIndex();
					List<String> list =  bean.getUrls();

					UCommonUtil.getUtil().startImagePagerActivity(activity, list, index, false);
				}
			}
		});

		//网页里 点击右上角 底部弹出的操作菜单 分享或者举报
		webView.registerHandler("setupMenus", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				//显示接收的消息
				Log.d("jjf", "分享数据=="+data);
				if (!TextUtils.isEmpty(data)){
					setupMenusBean = JsonUtils.getManager().stringToBean(data, SetupMenusBean.class);
					if (setupMenusBean.isOpen()){
						//立马打开底部选择框
						if (activity instanceof AllBaseActivity){
							if (activity.getWindow().getDecorView() != null){
								MoreOperateUtils.getUtils().more(activity, activity.getWindow().getDecorView(), setupMenusBean);
							}
						}
					}
				}
			}
		});

		//网页里 点击底部 打开软键盘 再将输入的文字返回
		webView.registerHandler("openEdit", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				//显示接收的消息
				if (activity instanceof LoadCycleWebHtmlActivity){
					((LoadCycleWebHtmlActivity)activity).openEdit(function, data);

				}

			}
		});

		//网页里 打开播放视频
		webView.registerHandler("openVideoPlayer", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				//显示接收的消息
				Log.d("jjf", "视频信息=="+data);
				Intent intent =new Intent(activity, PlayVideoCustomActivity.class);
				intent.putExtra(BaseConfig.VIDEO_ID, data);
				activity.startActivity(intent);
			}
		});

		//网页里 获取定位信息
		webView.registerHandler("getLocationInfo", new BridgeHandler() {
			@Override
			public void handler(String data, final CallBackFunction function) {
				//显示接收的消息
				Log.d("jjf", "------------>获取定位信息");
				if (activity instanceof LoadCycleWebHtmlActivity){
					((LoadCycleWebHtmlActivity)activity).getLocation(new OnResultListener() {
						@Override
						public void onResult(int stutas, String msg, int total, String data) {
							if (!TextUtils.isEmpty(data)){
								function.onCallBack(data);
							}
						}
					});
				}
			}
		});


		//网页里打开聊天界面
		webView.registerHandler("openChatActivity", new BridgeHandler() {
			@Override
			public void handler(String data, final CallBackFunction function) {
				//显示接收的消息
				Log.d("jjf", "h5给的用户信息=="+data);
				if (!TextUtils.isEmpty(data)){
					JSONObject jsonObject = JsonUtils.getManager().getJSONObject(data);
					long uid = jsonObject.getLongValue(BaseConfig.UID);
					String nickName = jsonObject.getString(BaseConfig.NICK_NAME);
					int chatType = jsonObject.getIntValue("chatType");//1单聊 2群聊
					switch (chatType){
						case 1:
							UCommonUtil.getUtil().toChatActiviy(activity, uid, Conversation.ConversationType.PRIVATE, nickName);
							break;
						case 2:
							UCommonUtil.getUtil().toChatActiviy(activity, uid, Conversation.ConversationType.GROUP, nickName);
							break;
					}
				}

			}
		});

		//网页里获取手机信息
		webView.registerHandler("getPhoneInfo", new BridgeHandler() {
			@Override
			public void handler(String data, final CallBackFunction function) {
				//显示接收的消息
				Map<String, String> map = new HashMap<>();
				map.put("appVersion", UCommonUtil.getUtil().getVersionName(activity));
				map.put("brand", Build.BRAND);
				map.put("model", Build.MODEL);
				String mapString = JsonUtils.getManager().MapToString(map);
				Log.d("jjf", "返回的手机信息=="+mapString);
				function.onCallBack(mapString);

			}
		});

		//网页里打开发布会场界面 活动关联会场
		webView.registerHandler("actLinkEvent", new BridgeHandler() {
			@Override
			public void handler(String data, final CallBackFunction function) {
				//显示接收的消息
				if (!TextUtils.isEmpty(data)){
					ActLinkEventBean bean = JsonUtils.getManager().stringToBean(data, ActLinkEventBean.class);
					if (bean != null){
						Intent intent = new Intent(activity, ReleaseRoomMeetActivity.class);
						intent.putExtra(BaseConfig.ACT_BASE_ID, bean.getId());
						intent.putExtra(BaseConfig.ACT_NAME, bean.getActName());
						intent.putExtra(BaseConfig.ACT_COVER, bean.getActCover());
						activity.startActivity(intent);
					}


				}

			}
		});

		//选择视频 上传成功 获取视频信息
		webView.registerHandler("chooseVideo", new BridgeHandler() {
			@Override
			public void handler(String data, final CallBackFunction function) {
				ChooseVideoActivity.setCallBackFunction(function);
				Intent intent  = new Intent(activity, ChooseVideoActivity.class);
				intent.putExtra(BaseConfig.IS_RETURN, true);
				activity.startActivity(intent);

			}
		});

		//根据网址url  获取title等信息  返回h5
		webView.registerHandler("getWebInfoTitle", new BridgeHandler() {
			@Override
			public void handler(final String data, final CallBackFunction function) {
				Log.d("jjf", "h5的网址=="+data);
				ExecutorsUtils.getUtils().createSingleThread().execute(new Runnable() {
					@Override
					public void run() {
						Document doc = null;
						try {
							doc = Jsoup.connect(data).get();
							String  title = doc.title();

							if (TextUtils.isEmpty(title)){
								Element element = doc.getElementsByTag("h1").first();
								title = element != null? StringUtil.normaliseWhitespace(element.text()).trim():"";
							}

							if (TextUtils.isEmpty(title)){
								Element element = doc.getElementsByTag("h2").first();
								title = element != null? StringUtil.normaliseWhitespace(element.text()).trim():"";
							}

							if (TextUtils.isEmpty(title)){
								Element element = doc.getElementsByTag("h3").first();
								title = element != null? StringUtil.normaliseWhitespace(element.text()).trim():"";
							}

							final String finalTitle = title;
							activity.runOnUiThread(new Runnable() {
									@Override
									public void run() {
										function.onCallBack(finalTitle);
									}
								});
						} catch (Exception e) {
							e.printStackTrace();
							activity.runOnUiThread(new Runnable() {
								@Override
								public void run() {
									function.onCallBack(null);
								}
							});
						}
					}
				});
			}
		});



	}

	public SetupMenusBean getSetupMenusBean(){
		return setupMenusBean;
	}

	public void setSetupMenusBeanNull(){
		setupMenusBean = null;
	}

	//清除上次打开的url地址 防止退出后 不能再次打开h5界面
	public void clearUrl(){
		System.out.println("清空:"+this);
		lastUrl = null;
	}
}
